package com.example.eat.ui;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.eat.R;
import com.example.eat.dao.RecipeDao;
import com.example.eat.model.Recipe;
import com.squareup.picasso.Picasso;

public class RecipeDetailActivity extends AppCompatActivity {
    private int recipeId;
    private RecipeDao recipeDao;
    private ImageButton imageButtonFavorite;
    private Recipe recipe;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.item_recipe);

        recipeId = getIntent().getIntExtra("recipeId", -1);
        if (recipeId == -1) {
            finish();
            return;
        }

        recipeDao = new RecipeDao(this);
        recipe = recipeDao.getRecipeById(recipeId);

        if (recipe == null) {
            finish();
            return;
        }

        ImageView imageViewRecipe = findViewById(R.id.imageViewRecipe);
        TextView textViewName = findViewById(R.id.textViewName);
        TextView textViewCategory = findViewById(R.id.textViewCategory);
        TextView textViewInstructions = findViewById(R.id.textViewInstructions);
        imageButtonFavorite = findViewById(R.id.imageButtonFavorite);

        if (recipe.getImage() != null && !recipe.getImage().isEmpty()) {
            Picasso.get().load(recipe.getImage()).into(imageViewRecipe);
        }

        textViewName.setText(recipe.getName());
        textViewCategory.setText(recipe.getCategory());
        textViewInstructions.setText(recipe.getInstructions());

        updateFavoriteIcon();

        imageButtonFavorite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleFavorite();
            }
        });
    }

    private void updateFavoriteIcon() {
        int favoriteIcon = recipe.isFavorite() ? R.drawable.ic_favorite : R.drawable.ic_favorite_border;
        imageButtonFavorite.setImageResource(favoriteIcon);
    }

    private void toggleFavorite() {
        recipe.setFavorite(!recipe.isFavorite());
        recipeDao.updateRecipe(recipe);
        updateFavoriteIcon();

        String message = recipe.isFavorite() ? "已收藏" : "已取消收藏";
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
}